//
//  CoolLocationManager.m
//  CoolFramework
//
//  Created by Felix on 13-4-5.
//  Copyright (c) 2013年 FelixApp. All rights reserved.
//

#import <MapKit/MapKit.h>
#import "CoolLocationManager.h"

@interface CoolLocationManager () <CLLocationManagerDelegate> {
    CLLocationManager   *locationManager_;
}

@end

@implementation CoolLocationManager
@synthesize locationManager = locationManager_;

+ (CoolLocationManager*)defaultManager {
    static CoolLocationManager  *s_DefaultManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_DefaultManager = [[CoolLocationManager alloc] init];
    });
    return s_DefaultManager;
}

- (void)startUpdatingLocation {
    if (locationManager_) {
        return;
    }
    locationManager_ = [[CLLocationManager alloc] init];
    
    locationManager_.delegate = self;
    
//    locationManager_.distanceFilter = 1;
    
    locationManager_.desiredAccuracy = kCLLocationAccuracyBest;
    
    [locationManager_ startUpdatingLocation];
}

- (void)stopUpdatingLocation {
    [locationManager_ stopUpdatingLocation];
    locationManager_ = nil;
}

- (void)reverseGeocodeLocation:(CLLocation*)location {
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    _currentLocation = location;
    [geoCoder reverseGeocodeLocation:location
                   completionHandler:^(NSArray *placemarks, NSError *error) {
                       if ([placemarks count] == 0) {
                           return;
                       }
                       _currentPlaceMark = placemarks[0];
                       [[NSNotificationCenter defaultCenter] postNotificationName:CoolLocationManagerDidUpdateLocationNotification object:nil userInfo:nil];
                   }];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    [self reverseGeocodeLocation:newLocation];
}

- (void)locationManager:(CLLocationManager *)manager
	 didUpdateLocations:(NSArray *)locations {
    if (locations.count > 0) {
        [self reverseGeocodeLocation:locations[0]];
    }
}


NSString * const CoolLocationManagerDidUpdateLocationNotification   = @"CoolLocationManagerDidUpdateLocationNotification";

@end
